function onPageLoad(event) {
  if (event.originalTarget instanceof HTMLDocument) {
    if (!event.originalTarget.defaultView.frameElement) {
      var count = TailsParser.parse(event.originalTarget);
 
      var tab = Browser.getTabForDocument(event.originalTarget);
      if (tab) tab.__tails_objectsFound = count;

      if (Browser.isCurrentTab(tab)) {
        onTabChanged(null);
      }
    }
  }
}
function onTabChanged(event) {
  OverlayControl.hide();
  var tab = Browser.getSelectedTab();
  if (tab.__tails_objectsFound > 0) {
    $$("tails-urlbutton").setAttribute("style", "display: block;");
    Tails.setStatus('logo_on', 'status_objects_found', [String(tab.__tails_objectsFound)]);
  } else {
    $$("tails-urlbutton").setAttribute("style", "display: none;");
    Tails.setStatus('logo_off', 'status_objects_not_found');
  }
}

var Tails = {
  /* nsISupports interface */
  QueryInterface: function(aIID) {
    if (!aIID.equals(Components.interfaces.nsISupports) &&
        !aIID.equals(Components.interfaces.nsISupportsWeakReference))
      throw Components.results.NS_ERROR_NO_INTERFACE;
    return this;
  },

  init: function() {
    window.removeEventListener("load", Tails.init, false);
    window.addEventListener("unload", Tails.deinit, false);

    Browser.addPageLoadListener(onPageLoad);
    Browser.addTabChangeListener(onTabChanged);

    // hook various events
    TailsNS.listen($$("appcontent"), "DOMContentLoaded", TailsNS.listener(Tails, "_contentLoad"));
    TailsNS.listen($$("contentAreaContextMenu"), "popupshowing", TailsNS.listener(Tails, "_contextMenuShowing"));

    Tails._addObserver();

    // we use this to determine if we are the active window sometimes
    Tails.winWat = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
        .getService(Components.interfaces.nsIWindowWatcher);
  },
  deinit: function() {
    Tails._removeObserver();

    TailsNS.unlisten($$("appcontent"), "DOMContentLoaded", Tails.__listeners["_contentLoad"]);
    TailsNS.unlisten($$("contentAreaContextMenu"), "popupshowing", Tails.__listeners["_contextMenuShowing"]);

    Browser.removeTabChangeListener(onTabChanged);
    Browser.removePageLoadListener(onPageLoad);

    window.removeEventListener("unload", Tails.deinit, false);
  },
  _contextMenuShowing: function() {
    var contextItem = $$("installTailsScript");
    var contextSep = $$("installTailsScriptSep");

    var culprit = document.popupNode;

    while (culprit && culprit.tagName && culprit.tagName.toLowerCase() != "a") {
      culprit = culprit.parentNode;
    }

    contextItem.hidden = contextSep.hidden = !this._getTailsScriptLinkUnderPointer();
  }, 
  _contentLoad: function(e) {
    var win = e.target.defaultView;
    var href = e.target.location.href;

    if (href.match(/\.tails\.js($|\?)/i)) {
      tabBrowser = $$("content");
      // find the browser the tails script is loading in
      for (var i = 0, browser; browser = tabBrowser.browsers[i]; i++) {
        if (browser.contentWindow == win) {
          if (tabBrowser.showMessage) {
	        tabBrowser.showMessage(
		        browser,
		        "chrome://tails/content/images/logo_on.gif",
		        TailsNS.getMessage("install.message"),
		        "Install",
		        null /* default doc shell */,
		        "installTailsScript",
		        null /* no popuup */,
		        "top",
		        true /* show close button */,
	            "I" /* access key */);
	      } else {
	        // Firefox 2.0+
            var notificationBox = tabBrowser.getNotificationBox(browser);

            // Remove existing notifications. Notifications get removed
            // automatically onclick and on page navigation, but we need to remove
            // them ourselves in the case of reload, or they stack up.
           for (var i = 0, child; child = notificationBox.childNodes[i]; i++) {
             if (child.getAttribute("value") == "installTailsScript") {
               notificationBox.removeNotification(child);
             }
           }

           var notification = notificationBox.appendNotification(
               TailsNS.getMessage("install.message"),
               "installTailsScript",
               "chrome://tails/content/images/logo_on.gif",
               notificationBox.PRIORITY_WARNING_MEDIUM,
               [{ label: 'Install', accessKey: "I",
               popup: null,
               callback: TailsNS.listener(this, "_installCurrentScript")}]);
	      }
          break;
        }
      }
    }
  },

  _getTailsScriptLinkUnderPointer: function() {
    var contextItem = $$("installTailsScript");
    var contextSep = $$("installTailsScriptSep");

    var culprit = document.popupNode;

    while (culprit && culprit.tagName && culprit.tagName.toLowerCase() != "a") {
      culprit = culprit.parentNode;
    }

    if (culprit && culprit.href && culprit.href.match(/\.tails\.js(\?|$)/i) != null) {
      return culprit;
    } else {
      return null;
    }
  },


  installContextItemClicked: function() {
    new Tails_ScriptDownloader().installFromURL(
        Tails._getTailsScriptLinkUnderPointer().href);
  },


  /* nsIObserver methods */
  observe: function(subject, topic, data) {
    if (topic == "installTailsScript") {
      this._installCurrentScript();
    } else {
      throw new Error("Unexpected topic received: {" + topic + "}");
    }
  },
  _installCurrentScript: function() {
    if (window == this.winWat.activeWindow) {
      new Tails_ScriptDownloader().installFromURL(
          $$("content").selectedBrowser.contentWindow.location.href);
    }
  },
  _addObserver: function() {
    // listen for clicks on the install bar
    Components.classes["@mozilla.org/observer-service;1"]
        .getService(Components.interfaces.nsIObserverService)
        .addObserver(Tails, "installTailsScript", true);
  },
  _removeObserver: function() {
    Components.classes["@mozilla.org/observer-service;1"]
        .getService(Components.interfaces.nsIObserverService)
        .removeObserver(Tails, "installTailsScript");
  },


  manage: function() {
    window.openDialog("chrome://tails/content/manage.xul", "manager",
        "resizable,centerscreen,modal");
  },

  setStatusMessage: function(msg) {
    var msgLabel = $$("tailsStatusMessage");
    msgLabel.hidden = !msg;
    msgLabel.value = msg;
  },
  setStatus: function(icon, tooltip, tooltipArgs) {
    var status = $$("tailsStatusImage");
    status.setAttribute("src", "chrome://tails/content/images/"+icon+".gif");
    status.setAttribute("tooltiptext", TailsNS.getMessage(tooltip, tooltipArgs));
  },

  toggleObjects: function() {
    if (OverlayControl.isVisible()) {
      OverlayControl.hide();
    } else {
      this.showObjects();
    }
  },
  showObjects: function() {
    var tab = Browser.getSelectedTab();
    if (tab.__tails_objectsFound > 0) {
      OverlayControl.show()
      this._loadObjects(Browser.getCurrentDocument());
    }
  },

  _loadObjects: function(doc) {
    TailsParser.parse(doc, function(format, node) {
      OverlayControl.objectList.addObject(format.parseObject(node));
    });
  },

  end: null 
};

window.addEventListener("load", Tails.init, false);
